package org.littlesun.management.address;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;

@AllArgsConstructor
public class CityMatcher {

	private MatchResult parent;
	private Collection<City> cities;
	
	public CityMatcher(City... cities) {
		this(null, cities);
	}
	
	public CityMatcher(Collection<City> cities) {
		this(null, cities);
	}

	public CityMatcher(MatchResult parent, City... cities) {
		this(parent, Arrays.asList(cities));
	}
	
	public MatchResult match(String text) {
		text = text.trim();
		MatchResult result = matchCityName(text);
		if (result.isSuccess() == false) {
			result = matchCityAlias(text);
		}
		if (result.isSuccess() == false) {
			result.addSuggestions(getSuggestions());
		}
		return result;
	}
	
	private MatchResult matchCityName(String text) {
		text = text.trim();
		for(City city : cities) {
			if (StringUtils.startsWith(text, city.getName())) {
				return new MatchResult(parent, city, city.getName(), text.substring(city.getName().length()));
			}
		}
		return new MatchResult(parent, null, "", text);
	}

	protected List<String> getSuggestions() {
		String matchedOrginalText = parent == null? "" : parent.getFullMatchedOrginalText();
		List<String> names = new ArrayList<String>();
		for(City city : cities) {
			names.add(matchedOrginalText + city.getName());
		}
		return names;
	}

	private MatchResult matchCityAlias(String text) {
		text = text.trim();
		for(City city : cities) {
			for(String alias : city.getAliases()) {
				if (StringUtils.startsWith(text, alias)) {
					return new MatchResult(parent, city, alias, text.substring(alias.length()));
				}
			}
		}
		return new MatchResult(parent, null, "", text);
	}

}
